package com.cfweb.pojo;

import java.util.Date;

import javax.servlet.http.HttpSession;

import com.cfweb.api.OauthApi;
import com.cfweb.controller.LoginHandler;

public class OauthToken {
	
	private String accessToken;
	
	private String tokenType;
	
	private String refreshToken;
	
	private int timeout;
	
	private Date createTime;

	public OauthToken(String accessToken, String tokenType, String refreshToken,int timeout) {
		super();
		this.accessToken = accessToken;
		this.tokenType = tokenType;
		this.refreshToken = refreshToken;
		this.timeout=timeout;
		this.createTime=new Date();
	}

	public String getAccessToken() {
		return accessToken;
	}

	public void setAccessToken(String accessToken) {
		this.accessToken = accessToken;
	}

	public String getTokenType() {
		return tokenType;
	}

	public void setTokenType(String tokenType) {
		this.tokenType = tokenType;
	}

	public String getRefreshToken() {
		return refreshToken;
	}

	public void setRefreshToken(String refreshToken) {
		this.refreshToken = refreshToken;
	}

	public int getTimeout() {
		return timeout;
	}

	public void setTimeout(int timeout) {
		this.timeout = timeout;
	}
	
	public int getExpirationIn(){
		return timeout==0?0:timeout-Long.valueOf(((System.currentTimeMillis()-createTime.getTime())/1000)).intValue();
	}
	
	public String getToken(HttpSession session) throws Exception{
		if(getExpirationIn()<120){
			OauthToken oauthToken=OauthApi.refreshToken(refreshToken, session);
			session.setAttribute(LoginHandler.TOKEN, oauthToken);
			return oauthToken.getAccessToken();
		}
		return this.accessToken;
	}

}
